package com.kotodama.infrastructure.config;

import com.kotodama.infrastructure.tenant.filter.TenantFilterInterceptor;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceUnit;

/**
 * JPA配置类，注册Hibernate事件监听器
 */
@Configuration
@EnableJpaRepositories(basePackages = "com.kotodama.domain.repositories")
public class JpaConfig {

        @PersistenceUnit
        private EntityManagerFactory entityManagerFactory;

        @Autowired
        private TenantFilterInterceptor tenantFilterInterceptor;

        /**
         * 注册租户过滤器事件监听器
         */
        @PostConstruct
        public void registerListeners() {
                SessionFactoryImpl sessionFactory = entityManagerFactory.unwrap(SessionFactoryImpl.class);
                EventListenerRegistry registry = sessionFactory.getServiceRegistry()
                                .getService(EventListenerRegistry.class);

                // 注册预加载和后加载事件监听器
                registry.getEventListenerGroup(EventType.PRE_LOAD)
                                .appendListener(tenantFilterInterceptor);
                registry.getEventListenerGroup(EventType.POST_LOAD)
                                .appendListener(tenantFilterInterceptor);
        }
}